package com.isoft.airportsystem.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.airportsystem.entity.system.User;
import com.isoft.airportsystem.entity.system.UserRole;
import com.isoft.airportsystem.entity.system.Role;
import com.isoft.airportsystem.mapper.system.UserMapper;
import com.isoft.airportsystem.mapper.system.UserRoleMapper;
import com.isoft.airportsystem.mapper.system.RoleMapper;
import com.isoft.airportsystem.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Page<User> selectUserPage(Page<User> page, User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (user != null) {
            if (StringUtils.hasText(user.getUsername())) {
                queryWrapper.like(User::getUsername, user.getUsername());
            }
            if (StringUtils.hasText(user.getRealName())) {
                queryWrapper.like(User::getRealName, user.getRealName());
            }
            if (StringUtils.hasText(user.getPhone())) {
                queryWrapper.like(User::getPhone, user.getPhone());
            }
            if (user.getStatus() != null) {
                queryWrapper.eq(User::getStatus, user.getStatus());
            }
        }
        // 移除非删除状态过滤
        // queryWrapper.eq(User::getDelFlag, 0); // 注释掉这行

        queryWrapper.orderByDesc(User::getCreateTime);
        return page(page, queryWrapper);
    }

    @Override
    public User selectUserByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.eq(User::getDelFlag, 0);
        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertUser(User user, Long[] roleIds) {
        // 设置默认值
        user.setCreateTime(LocalDateTime.now());
        user.setDelFlag(0);
        // 保存用户信息
        boolean result = save(user);
        // 保存用户角色关联信息
        if (result && roleIds != null && roleIds.length > 0) {
            insertUserRole(user.getUserId(), roleIds);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user, Long[] roleIds) {
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        // 更新用户信息
        boolean result = updateById(user);
        // 删除原有用户角色关联
        if (result) {
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUserId, user.getUserId());
            userRoleMapper.delete(queryWrapper);
            // 保存新的用户角色关联信息
            if (roleIds != null && roleIds.length > 0) {
                insertUserRole(user.getUserId(), roleIds);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserById(Long userId) {
        // 物理删除前先删除关联数据
        LambdaQueryWrapper<UserRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.eq(UserRole::getUserId, userId);
        userRoleMapper.delete(roleWrapper);

        // 物理删除用户
        return removeById(userId);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserByIds(Long[] userIds) {
        // 批量删除关联数据
        LambdaQueryWrapper<UserRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.in(UserRole::getUserId, Arrays.asList(userIds));
        userRoleMapper.delete(roleWrapper);

        // 批量物理删除用户
        return removeByIds(Arrays.asList(userIds));
    }

    @Override
    public boolean resetPassword(Long userId, String password) {
        User user = new User();
        user.setUserId(userId);
        user.setPassword(password);
        user.setUpdateTime(LocalDateTime.now());
        return updateById(user);
    }

    @Override
    public boolean updateUserStatus(Long userId, Integer status) {
        User user = new User();
        user.setUserId(userId);
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        return updateById(user);
    }

    @Override
    public List<Long> selectRoleIdsByUserId(Long userId) {
        return baseMapper.selectRoleIdsByUserId(userId);
    }

    @Override
    public List<String> selectPermissionsByUserId(Long userId) {
        return baseMapper.selectPermissionsByUserId(userId);
    }

    /**
     * 批量新增用户角色关联
     *
     * @param userId  用户ID
     * @param roleIds 角色ID数组
     */
    private void insertUserRole(Long userId, Long[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            List<Long> roleIdsList = Arrays.asList(roleIds);
            userRoleMapper.batchInsert(userId, roleIdsList);
        }
    }
    @Override
    public User selectUserById(Long userId) {
        return baseMapper.selectById(userId);
    }
    @Override
    public boolean updateUserSelective(User user) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, user.getUserId())
                // 替代 StringUtils.isNotBlank(user.getUsername())
                .set(user.getUsername() != null && !user.getUsername().trim().isEmpty(),
                        User::getUsername,
                        user.getUsername())
                // 添加真实姓名字段
                .set(user.getRealName() != null && !user.getRealName().trim().isEmpty(),
                        User::getRealName,
                        user.getRealName())
                // 替代 StringUtils.isNotBlank(user.getPhone())
                .set(user.getPhone() != null && !user.getPhone().trim().isEmpty(),
                        User::getPhone,
                        user.getPhone())
                // 替代 StringUtils.isNotBlank(user.getEmail())
                .set(user.getEmail() != null && !user.getEmail().trim().isEmpty(),
                        User::getEmail,
                        user.getEmail())
                // 添加备注字段
                .set(user.getRemark() != null && !user.getRemark().trim().isEmpty(),
                        User::getRemark,
                        user.getRemark())
                // 状态字段判断（保持不变）
                .set(user.getStatus() != null,
                        User::getStatus,
                        user.getStatus())
                // 密码字段判断（替代 StringUtils.isNotBlank(user.getPassword())）
                .set(user.getPassword() != null && !user.getPassword().trim().isEmpty(),
                        User::getPassword,
                        user.getPassword())
                // 设置更新时间
                .set(User::getUpdateTime, LocalDateTime.now());

        return update(updateWrapper);
    }

    @Override
    public List<Role> selectRolesByUserId(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    public List<User> selectAllUsers() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询启用状态的用户
        queryWrapper.eq(User::getStatus, 1);
        // 按用户名排序
        queryWrapper.orderByAsc(User::getUsername);
        return list(queryWrapper);
    }
}